type TodoItem = {
  id: number;
  task: string;
  isDone: boolean;
};
const initialState = {
  // 4.1 初始化数据
  // 14.3 从缓存中取出数据
  list: JSON.parse(localStorage.getItem('todo-list') || '[]') as TodoItem[], // 14.4 断言TodoItem与TodoFilterType
  // 9.1 state中声明type变量
  type: (localStorage.getItem('todo-type') || 'all') as TodoFilterType, // 9.3 使用as断言，明确告诉ts这是TodoFilterType
};
// 9.2 定义type的类型为联合类型
export type TodoFilterType = 'all' | 'active' | 'completed';

// 5.2 定义ActionType类型，
export type TodoAction =
  | { type: 'todo/delById'; payload: number }
  // 6.1 定义TodoAction中的更新类型
  | { type: 'todo/updateById'; payload: number }
  // 7.1 定义TodoAction中清除类型
  | { type: 'todo/clearIdDone' }
  // 10.1 定义修改type的Action
  | { type: 'todo/selectType'; payload: TodoFilterType }
  // 13.1 新增Action类型
  | { type: 'todo/addTodo'; payload: string }
  // 16.2 定义TodoAction联合类型
  | { type: 'todo/checkedAll'; payload: boolean };

// 💥脚手架中，不允许有隐式any .🔔 手动先加上any
// 7.2 👍 推荐不要解构aciton
export default function todoReducer(state = initialState, action: TodoAction): typeof initialState {
  // 5.1 加上switch分支
  switch (action.type) {
    case 'todo/delById':
      // 删除的逻辑最后来写
      return {
        ...state,
        list: state.list.filter((item) => item.id !== action.payload),
      };
    // 6.2 reducer定义更新的逻辑分支
    case 'todo/updateById':
      return {
        ...state,
        // 6.5 完成更新isDone的逻辑
        list: state.list.map((item) => ({
          ...item,
          isDone: item.id === action.payload ? !item.isDone : item.isDone,
        })),
      };
    // 7.3 定义分支逻辑
    case 'todo/clearIdDone':
      return {
        ...state,
        list: state.list.filter((item) => !item.isDone),
      };

    // 10.2 修改的分支逻辑
    case 'todo/selectType':
      return {
        ...state,
        type: action.payload,
      };
    // 13.2 新增的reducer计算分支
    case 'todo/addTodo':
      return {
        ...state,
        list: [{ id: Date.now(), task: action.payload, isDone: false }, ...state.list],
      };
    // // 16.3 reducer中增加switch分支逻辑
    case 'todo/checkedAll':
      return {
        ...state,
        list: state.list.map((item) => ({ ...item, isDone: action.payload })),
      };

    default:
      return state;
  }
}
